#include <iostream>
#include <memory>

class Data
{
private:
    int a{};

public:
    void func()
    {
        std::cout << "func() 函数调用了~" << std::endl;
    }

    Data()
    {
        std::cout << "构造函数调用了~" << std::endl;
    }
    ~Data()
    {
        std::cout << "析构函数调用了~" << std::endl;
    }

    Data(int a)
    {
        this->a = a;
    }

    void showInt()
    {
        std::cout << "a = " << this->a << std::endl;
    }
};

class SmartPointer
{
private:
    Data *p;

public:
    SmartPointer(Data *p)
    {
        this->p = p;
    }

    ~SmartPointer()
    {
        if (p != nullptr)
        {
            delete p;
            p = nullptr;
        }
    }

    Data *operator->()
    {
        return p;
    }
};

int main(int argc, char const *argv[])
{
    // 使用裸指针和delete
    Data *data = new Data();
    data->func();
    delete data;

    std::cout << std::string(30, '#') << std::endl;

    // 使用自定义的 SmartPointer
    SmartPointer smartPointer = SmartPointer(new Data());
    smartPointer->func();
    std::cout << std::string(30, '#') << std::endl;

    // 使用 std::shared_ptr
    std::shared_ptr<Data> dataPointer = std::shared_ptr<Data>(new Data());
    dataPointer->func();
    std::cout << std::string(30, '#') << std::endl;

    // 使用 std::make_shared，避免了显式使用 new
    std::shared_ptr<Data> dataPointer2 = std::make_shared<Data>(123);
    dataPointer2->func();
    dataPointer2->showInt();

    return 0;
}
